﻿using MediatR;
using System.Threading;
using System.Threading.Tasks;
using System.Net.Http;
using Microsoft.Extensions.Options;
using Casamiel.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;

namespace Casamiel.Application.Commands
{

    /// <summary>
    /// 
    /// </summary>
    public sealed  class TmallCheckTokenCommandHandler:BaseCommandHandler,IRequestHandler<TmallCheckTokenCommand,bool>
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="netICService"></param>
        /// <param name="httpClientFactory"></param>
        /// <param name="optionsSnapshot"></param>
        public TmallCheckTokenCommandHandler(INetICService netICService, IHttpClientFactory httpClientFactory, IOptionsSnapshot<CasamielSettings> optionsSnapshot)
       : base(netICService, httpClientFactory, optionsSnapshot)
        {
            
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<bool> Handle(TmallCheckTokenCommand request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            var url = "TPP/v1/Account/CheckToken";
            var data = new { request.Token, storeBaseId = 0 };
            var result = await PostThirdApiAsync<string>(url, JsonConvert.SerializeObject(data)).ConfigureAwait(false);
            if (result.Code != 0)
            {
                return false;
            }
            //var rsp = JsonConvert.DeserializeObject<JObject>(result);
            //if (rsp["resultNo"].ToString() != "00000000")
            //{
            //    return false;
            //}
            return true;
        }
    }
}
